import vscode from "vscode";
import * as path from 'path';

import {utf8ArrayToStr} from "./util";
/**
 * 获取Json文件
 */
export const getStoreJson = (path: vscode.Uri,name:string, defaultVal?:any): Promise<any> => {
    return new Promise((resolve, reject) => {
        vscode.workspace.fs.readFile(vscode.Uri.joinPath(path, name + '.json')).then((data) => {
            const dataString = utf8ArrayToStr(data);
            try {
                const json = JSON.parse(dataString);
                resolve(json);
            } catch (error) {
                resolve(defaultVal);
            }
        }, () => {
            resolve(defaultVal);
        })
    })
}

/**
 * 设置Json文件
 */
export const setStoreJson = (path:  vscode.Uri,name:string, value: any): Promise<any> => {
    return new Promise((resolve, reject) => {
        const encoder = new TextEncoder();
        vscode.workspace.fs.writeFile(vscode.Uri.joinPath(path, name + '.json'), encoder.encode(JSON.stringify(value))).then(() => {
          resolve(true);
        }, () => {
          resolve(false);
        })
    })
}

